package com.test.juc.resource;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Share {

    private int shareNumber = 0;
    private final Lock lock;
    private final Condition condition;

    public Share() {
        lock = new ReentrantLock();
        condition = lock.newCondition();
    }

    public Share(boolean isFair) {
        lock = new ReentrantLock(isFair);
        condition = lock.newCondition();
    }

    public synchronized void incr() throws InterruptedException {
        while (shareNumber != 0) {
            this.wait();
        }

        shareNumber++;
        System.out.printf("%s :: %d\n", Thread.currentThread().getName(), shareNumber);
        this.notifyAll();
    }

    public synchronized void decr() throws InterruptedException {
        while (shareNumber < 1) {
            this.wait();
        }

        shareNumber--;
        System.out.printf("%s :: %d\n", Thread.currentThread().getName(), shareNumber);
        this.notifyAll();
    }

    public void lockIncr() throws InterruptedException {
        lock.lock();
        try {
            while (shareNumber != 0) {
                condition.await();
            }

            shareNumber++;
            System.out.printf("%s :: %d\n", Thread.currentThread().getName(), shareNumber);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void lockDecr() throws InterruptedException {
        lock.lock();
        try {
            while (shareNumber < 1) {
                condition.await();
            }

            shareNumber--;
            System.out.printf("%s :: %d\n", Thread.currentThread().getName(), shareNumber);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
